<!-- 编辑弹窗 -->
<template>
    <ele-modal
      inner
      fullscreen
      :movable="false"
      :visible="visible"
      :close-on-click-modal="true"
      :before-close="handleClose"
      custom-class="ele-dialog-form"
      :title="isUpdate ? '修改入库单信息' : '添加入库单信息'"
      @update:visible="updateVisible" 
    >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  >  
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >基础信息</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div v-show="form.inOrderNo!='' && form.inOrderNo!=null" style="width: 30%;color:var(--color-primary)" >入库单号:{{ form.inOrderNo }}</div>
          </div>
        </div>      
        <el-row :gutter="24">
          <el-col :md="6" :sm="24" >
            <el-form-item label="入库日期:"  prop="inDate">
              <el-date-picker v-model="form.inDate" type="date" placeholder="请输入入库日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="经办人:" prop="operatorId">
              <el-select  v-model="form.operatorId" filterable placeholder="请选择制单人" style="width:100%" @change="selectoperate" >
                <el-option  v-for="item in accountDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="入库金额:"  >
              <el-input v-model="form.inAmount" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="清关费用:"  >
              <el-input v-model="form.clearAmount"   disabled/>
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="24" >
            <el-form-item label="备注:"  >
              <el-input :rows="2"
                  clearable
                  type="textarea"
                  :maxlength="200"
                  v-model="form.remark"
                  placeholder="请输入备注说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >入库明细列表</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div style="width: 30%;color:var(--color-primary)" > 
                <el-button icon="el-icon-plus" style="width: 100%;" @click="OpenProductList"  >选择采购订单 </el-button>
              </div>
          </div>
        </div> 
        <el-table :data="form.items" ref="items"  :border="true" style="width: 100%" :height="tableHeight" :full-height="tableFullHeight">
          <el-table-column type="index" width="50" align="center" label="序号" fixed='left' />
          <el-table-column label="订单号" width="150"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <!-- <span>{{ row.purOrderNo }}</span> -->
                  <el-link type="primary" v-show="row.status!=5"  :underline="false"    @click="clickOrderNo(row)" >{{ row.purOrderNo }}</el-link>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="产品编号" width="150"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productCode }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="产品名称" width="150"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productName }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="规格" align="center" width="100" >
            <template slot-scope="{ row }">
              <span>{{ row.spc }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" width="100">
              <template slot-scope="{ row }">
                  <span>{{ row.unitDesc }}</span>
              </template>
          </el-table-column>
          <el-table-column label="数量" align="center" width="100">
            <template slot-scope="{ row ,$index}">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.qty'" :rules="itemRules.qty" >
                <el-input  v-model="row.qty"  placeholder="请输入数量" @change="setAmount(row,$index)"  @keyup.native="row.qty = row.qty.replace(/[^\d.]/g,'');
                  row.qty = row.qty.replace(/\.{2,}/g,'.');
                  row.qty = row.qty.replace(/^\./g,'');
                  row.qty = row.qty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.qty = row.qty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="成本单价(￥)" align="center" width="150">
              <template slot-scope="{ row ,$index}">
                <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.costPrice'" :rules="itemRules.costPrice">
                  <el-input  v-model="row.costPrice"  placeholder="请输入成本单价"  @change="setAmount(row,$index)" @keyup.native="row.costPrice = row.costPrice.replace(/[^\d.]/g,'');
                  row.costPrice = row.costPrice.replace(/\.{2,}/g,'.');
                  row.costPrice = row.costPrice.replace(/^\./g,'');
                  row.costPrice = row.costPrice.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.costPrice = row.costPrice.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');" />
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="金额" align="center" width="120">
            <template slot-scope="{ row }">
              <span>{{ row.totalPrice }}</span>
              <!-- <el-form-item label-width="10" style="margin-bottom:0;" >
                <el-input  v-model="row.totalPrice"  prefix-icon="el-icon-_rmb" disabled />
              </el-form-item> -->
            </template>
          </el-table-column>
          <el-table-column label="集装箱号" align="center" width="150">
            <template slot-scope="{ row, $index }">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.containerNumber'" :rules="itemRules.containerNumber" >
                <el-input v-model="row.containerNumber" placeholder="请输入集装箱号" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="供应商" width="150"  align="center">
            <template slot-scope="{ row }">
              <el-form-item label-width="10" style="margin-bottom:0;" >
                <el-select  filterable v-model="row.supplierId" class="ele-fluid"  disabled>
                  <el-option v-for="item in supplierDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="仓库" align="center" width="150">
            <template slot-scope="{ row ,$index }">
              <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.wareHouseId'" :rules="itemRules.wareHouseId">
                <el-select  filterable v-model="row.wareHouseId" placeholder="请选择仓库" class="ele-fluid" >
                  <el-option v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="行备注" align="center" width="250">
            <template slot-scope="{ row }">
                <el-input  v-model="row.remarks" placeholder="请输入行备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :resizable="false" v-if="this.btnIndex!=3" fixed='right' >
            <template slot-scope="{ row , $index}">
              <span class="ele-action">
                <el-link  icon="el-icon-delete" type="danger" :underline="false" @click="remove(row, $index)" >删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card  style="margin-top: 10px">
        <!-- <div slot="header" class="clearfix" >费用明细</div> -->
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >费用明细 </div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div style="width: 30%;color:var(--color-primary)" > 
              <el-button v-show="form.costs==null || form.costs.length==0" icon="el-icon-plus" style="width: 100%;" @click="AddCost(true)"  >新增费用信息</el-button>
            </div>
          </div>
        </div> 
        <el-table :data="form.costs" ref="costs"  :border="true" style="width: 100%" >
          <el-table-column type="index" width="50" align="center" label="序号"   />
          <el-table-column label="费用名称" width="120" align="center" >
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <el-select  filterable clearable disabled v-model="row.costId" placeholder="请选择费用名称" class="ele-fluid">
                  <el-option v-for="item in costDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                  <!-- <span >{{ row.costDesc }}</span> -->
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="费用公司名称" width="150" align="center">
            <template slot-scope="{ row}">
              <el-form-item  label-width="10"  style="margin-bottom:0;" >
                <el-select  style="width: 100%;" disabled filterable clearable v-model="row.supplierId" placeholder="请选择费用公司"  @change="(v)=>changeThreeCompany(row,v,$index)" >
                  <el-option  v-for="item in QGCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>
              <!-- <span >{{ row.supplierDesc }}</span> :prop="'costs.'+ $index+'.supplierId'" :rules="costsRules.supplierId"-->
            </template>
          </el-table-column>
          <el-table-column label="币种" width="100" align="center">
            <template slot-scope="{ row }">
              <el-form-item label-width="10" style="margin-bottom:0;" >
                <el-select  filterable clearable disabled v-model="row.currencyId" placeholder="请选择币种" class="ele-fluid" @change="(v)=>changeCurrency(v,$index)">
                  <el-option v-for="item in hbDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <!-- {{ row.currencyDesc }} :prop="'costs.'+ $index+'.currencyId'" :rules="costsRules.currencyId" -->
            </template>
          </el-table-column>
          <el-table-column label="金额" width="150" align="center">
              <template slot-scope="{ row }">
                <!-- <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'costs.'+ $index+'.amount'" :rules="costsRules.amount">
                  <el-input v-model="row.amount" placeholder="请输入金额" @change="setExchangeAmount(row,$index)"  @keyup.native="row.amount = row.amount.replace(/[^\d.]/g,'');
                  row.amount = row.amount.replace(/\.{2,}/g,'.');
                  row.amount = row.amount.replace(/^\./g,'');
                  row.amount = row.amount.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.amount = row.amount.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                </el-form-item> -->
                <span>{{ row.amount }}</span>
              </template>
          </el-table-column>
          <el-table-column label="汇率" width="150" align="center">
            <template slot-scope="{ row }">
              <!-- <el-form-item label-width="10" style="margin-bottom:0;" :prop="'costs.'+ $index+'.rate'" :rules="row.currencyCode!='C-HB01'?costsRules.rate:null" >
                <el-input v-if="row.currencyCode!='C-HB01'"   v-model="row.rate" placeholder="请输入汇率" :disabled="row.currencyCode=='C-HB01'" @change="setExchangeAmount(row,$index)"  @keyup.native="row.rate = row.rate.replace(/[^\d.]/g,'');
                    row.rate = row.rate.replace(/\.{4,}/g,'.');
                    row.rate = row.rate.replace(/^\./g,'');
                    row.rate = row.rate.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                    row.rate = row.rate.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                <span v-else>{{  row.rate }}</span>
              </el-form-item> -->
              <span >{{  row.rate }}</span> 
            </template>
          </el-table-column>
          <el-table-column label="金额(￥)" width="150" align="center">
              <template slot-scope="{ row  }">
                <span>{{ row.amountCn }}</span>
                <!-- <el-form-item label-width="10" style="margin-bottom:0;"  >
                  <el-input v-model="row.amountCn" disabled/>
                </el-form-item> -->
              </template>
          </el-table-column>
          <el-table-column label="行备注" align="center">
            <template slot-scope="{ row }">
              <span >{{  row.remarks }}</span> 
                <!-- <el-input v-model="row.remarks" placeholder="请输入行备注" /> -->
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :resizable="false"  fixed='right' >
            <template slot-scope="{ row , $index}">
              <span class="ele-action">
                <el-link  icon="el-icon-edit" type="primary" :underline="false" @click="AddCost(false)" >修改 </el-link>
                <el-link  icon="el-icon-delete" type="danger" :underline="false" v-if="form.status == 1" @click="removeCost(row, $index)" >删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card shadow="never"> </el-card>
    </el-form>
    <div slot="footer">
     
      <el-button type="primary" v-show="this.btnIndex!=3 && form.status!=5"  :loading="loading"  @click="save" >
        挂单
      </el-button>
      <el-button type="warning" v-show="this.btnIndex!=3 && form.status!=5" :loading="loadingAudit" @click="audit">
        审核
      </el-button>
      <el-button type="danger" v-show="form.status==5"  @click="unAudit"  :loading="loadingUnAudit"  >
        反审核
      </el-button>
      <el-button type="info" @click="print" v-show="form.inOrderNo!='' && form.inOrderNo!=null">打印</el-button>
      <el-button  @click="handleClose">关闭</el-button>
    </div>
     <!-- 编辑弹窗 -->
     <purChooseList :visible.sync="showProductList"  @callback="reloadItemList"/>

     <costEdit :visible.sync="showAddCost"  @callback="reloadCostList" :data="current"/>
    </ele-modal>
  </template>
  <script>
   import { printHtml } from 'ele-admin';
   import costEdit from './cost-edit.vue';
   import purChooseList from './purchoose-list.vue';
   import { getUser } from '@/utils/user-util';
   import upload from "@/components/UpLoad/index.js";
   import { removePageTab } from '@/utils/page-tab-util';
   import { GetAllAccount } from '@/api/usermanager/accountmanager';
   import { QueryModelBycurrencyId } from '@/api/basicdatamanager/ratemanager';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { GetAllBSupplier, QuerySupplierByType} from '@/api/basicdatamanager/supplier';
   import { AddInorder, UpdateInorder,QueryInorderById,AuitInorder,PrintInOrderById,AntiInorder } from '@/api/inventory/inorder';
  

    export default {
      name: 'InstockComEdit',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      mixins: [upload],
      components: {purChooseList,costEdit},
      data() {
        return {
          
          // 表单数据
          form: {id:'',createUser:'',createDate:'',costs:[],clearAmount:0},
          // 表单验证规则
          rules: {
            wareHouseId: [{required: true,message: '请选择收货仓',trigger: 'blur'}],
            deliveryDate: [{required: true,message: '请输入发货日期',trigger: 'blur'}],
            // supplierId: [{required: true,message: '请选择供应商',trigger: 'blur'}],
            // contractNumber: [{required: true,message: '请输入合同号',trigger: 'blur'}],
          },
          itemRules: {
            qty: [{required: true,message: '请输入数量',trigger: 'blur'}],
            costPrice: [{required: true,message: '请输入成本单价',trigger: 'blur'}],
            containerNumber: [{required: true,message: '请输入集装箱',trigger: 'blur'}],
            wareHouseId: [{required: true,message: '请输入入库仓库',trigger: 'blur'}],
          },
          costsRules: {
            amount: [{required: true,message: '请输入金额',trigger: 'blur'}],
            rate: [{required: true,message: '请输入汇率',trigger: 'blur'}],
            currencyId: [{required: true,message: '请输入币种',trigger: 'blur'}],
            supplierId: [{required: true,message: '请输入第三方公司',trigger: 'blur'}],
          },
          fixedHeight:true,
          current:null,
          showAddCost:false,
          isShow:false,
          // 提交状态
          loading: false,
          loadingAudit: false,
          loadingUnAudit: false,
          // 是否是修改
          isUpdate: false,
          showProductList:false,
          defaultDate:new Date(),
          hbDatas:[],
          costDatas:[],
          accountDatas:[],
          supplierDatas:[],
          wareHouseDatas:[],
          QGCompanyDatas:[],
        };
      },
      computed: {
        // 表格高度
        tableHeight() {

          var fh = this.fixedHeight ? 'calc(100vh - 480px)' : void 0;
          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 380px)' : null;
          return fh;
        },
      },
      //初始化数据
      mounted(){
        this.initData();
      },
      methods: {

        /* 初始化数据 */
        initData(){

          GetAllAccount().then((res)=>{
            this.accountDatas = [];
            this.accountDatas = res;
          });

          //清关费
          QuerySupplierByType(3).then((res)=>{
            this.QGCompanyDatas = [];
            this.QGCompanyDatas = res;
          });

          QueryAllChildDictViewByCode(this.Constant.C_HB).then((res)=>{
            this.hbDatas = [];
            this.hbDatas = res;
          });

          QueryAllChildDictViewByCode(this.Constant.C_FYLX).then((res)=>{
            this.costDatas = [];
            this.costDatas = res;
          });

          GetAllWarehouse().then((res)=>{
            this.wareHouseDatas = [];
            this.wareHouseDatas = res;
          });

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            this.supplierDatas = res;
          });
        },

        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            this.setSharePrice();

            this.loading = true;
            const saveOrUpdate = this.isUpdate ? UpdateInorder : AddInorder;
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible(false);
                //回调父组件方法
                this.$emit('done');
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        /* 审核入库单 */
        audit(){
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            if(this.form.items==null || this.form.items==undefined || this.form.items.length==0){
              this.$message.info('产品列表不能为空');
              return;
            }

            this.setSharePrice();

            this.loadingAudit = true;
            AuitInorder(this.form)
              .then((msg) => {
                this.loadingAudit = false;
                this.$message.success(msg);
                this.updateVisible(false);
                //回调父组件方法
                this.$emit('done');
              })
              .catch((e) => {
                this.loadingAudit = false;
                this.$message.error(e.message);
              });
          });
        },

        unAudit(){
          this.loadingUnAudit = true;
          AntiInorder(this.form.id)
            .then((msg) => {
              this.loadingUnAudit = false;
              this.$message.success(msg);
              this.updateVisible(false);
              //回调父组件方法
              this.$emit('done');
            })
            .catch((e) => {
              this.loadingUnAudit = false;
              this.$message.error(e.message);
            });
        },

        
        //费用分摊
        //A产品采购金额10元
        //B产品采购金额20元
        //A/B产品总共产生了6元的运费
        //那么A产品分摊6÷（10+20）×10=2元
        //B产品分摊6÷（10+20）×20=4元
        setSharePrice(){
          var amount = 0
          var costAmountcn = 0;
          var inamount = parseFloat(this.form.inAmount);

          if(this.form.costs!=null && this.form.costs!=undefined){
            costAmountcn =  this.form.costs.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.amountCn)  },0);
          }

          if(this.form.items!=null && this.form.items!=undefined){
            amount = costAmountcn/inamount;
            this.form.items.map((item,index)=>{
              var amounttotal = amount * item.totalPrice;
              this.form.items[index].sharePrice = parseFloat(item.qty)<=0?0:(amounttotal/parseFloat(item.qty)).toFixed(4);
            })
          }
        },


        setData(id){
          QueryInorderById(id)
            .then((res) => {
              this.form = res; 
              this.setCostRequired(0);

              this.$nextTick(() => {
                this.$refs.items.doLayout();
              });
          });
        },

        selectoperate(val){
          let acc = this.accountDatas.find((v)=>{ return v.id == val });
          if(acc){
            this.form.operatorName = acc.name;
          }
        },

        OpenProductList(){
          this.showProductList =true;
        },

        reloadItemList(orderData){

          this.form.items = [];

          orderData.map((item)=>{
            this.form.items.push({
              purOrderId:item.purOrderId,
              purOrderNo:item.purOrderNo,
              inOrderId:this.form.id,
              productId:item.productId,
              unitId:item.unitId,
              qty:item.qty,
              costPrice:item.costPrice,
              totalPrice:item.totalPrice,
              sharePrice:item.sharePrice,
              purSharePrice:item.purSharePrice,
              wareHouseId:item.wareHouseId,
              containerNumber:item.containerNumber,
              wareHouseDesc:item.wareHouseDesc,
              productCode:item.productCode,
              productName:item.productName,
              spc:item.spc,
              unitDesc:item.unitDesc,
              supplierId:item.supplierId,
              purItemId:item.purItemId,
            })
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });

          this.setPurAmountTotal();
        },

        //
        reloadCostList(cost){
          if(cost){
            this.form.costs = [];
            this.form.costs.push(cost);
            this.form.clearAmount = cost.amount;
          }else{
            QueryInorderById(this.form.id).then((d)=>{
              this.form.costs = [];
              this.form.costs = d.costs;
              this.form.clearAmount = d.clearAmount;
            });

            this.$nextTick(() => {
              this.$refs.costs.doLayout();
            });
          }
        },

        changeCurrency(val,index){
          let hb = this.hbDatas.find((p)=>p.id === val)
          if(hb){
           this.$refs.costs.data[index].currencyCode = hb.code;
           if(hb.code == 'C-HB01'){
              this.$refs.costs.data[index].rate = 1;
              this.$refs.costs.data[index].amountCn = this.$refs.costs.data[index].amount;
           }else{
            QueryModelBycurrencyId(val).then((res)=>{
              this.$refs.costs.data[index].rate = res.rate;
              this.$refs.costs.data[index].amountCn = (this.$refs.costs.data[index].amount / res.rate ).toFixed(4);
            })
           }
          }

          this.setCostRequired(index);
        },

        setCostRequired(index){

          if(this.form.costs){
            if(this.form.costs[index].amount>0 || this.form.costs[index].rate>0||(this.form.costs[index].currencyId!=''&&this.form.costs[index].currencyId!=null) || (this.form.costs[index].supplierId!=''&&this.form.costs[index].supplierId!=null)){

              this.costsRules.amount = [{required: true,message: '请输入金额',trigger: 'blur'}];
              this.costsRules.rate = [{required: true,message: '请输入汇率',trigger: 'blur'}];
              this.costsRules.currencyId = [{required: true,message: '请输入币种',trigger: 'blur'}];
              this.costsRules.supplierId = [{required: true,message: '请输入第三方公司',trigger: 'blur'}];
              }else{
              this.costsRules.amount = null;
              this.costsRules.rate = null;
              this.costsRules.currencyId = null;
              this.costsRules.supplierId = null;
            }
          }
        },

        //选择第三方公司
        changeThreeCompany(row,val,index){
          let qgCompany = this.QGCompanyDatas.find((p)=>p.id === val)
          if(qgCompany){
            this.$refs.costs.data[index].rate = qgCompany.rate;
            this.$refs.costs.data[index].currencyId = qgCompany.currencyId;
            this.$refs.costs.data[index].supplierTypeId = qgCompany.typeId;
            this.changeCurrency(qgCompany.currencyId,index);
          }

          this.setCostRequired(index);
        },

        //设置金额
        setAmount(row,index){
          if(row.costPrice && row.qty){
              let qty = parseFloat(row.qty);
              let costPrice = parseFloat(row.costPrice);
              this.$refs.items.data[index].totalPrice = (costPrice * qty).toFixed(2);
          }

          this.setPurAmountTotal();
        },

        //设置入库金额
        setPurAmountTotal(){
          this.form.inAmount = 0;
          if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){
            this.form.inAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.totalPrice) },0);
            this.form.inAmount =this.form.inAmount.toFixed(4);
          }
        },

        setExchangeAmount(row,index){
          if(row.amount && row.rate){
              let rate = parseFloat(row.rate);
              let amount = parseFloat(row.amount);

              if(row.costNumber =='C-FYLX03')this.form.clearAmount = amount;  //港杂费

              if(row.currencyCode == 'C-HB01'){
                this.$refs.costs.data[index].rate =1;
                this.$refs.costs.data[index].amountCn = amount;
              }else{
                this.$refs.costs.data[index].amountCn = (amount/rate).toFixed(4);
              }
          }

          this.setCostRequired(index);
        },

        /* 删除 */
        remove(_row, index) {
          this.form.items.splice(index, 1);
          this.setPurAmountTotal();
        },

        /* 删除 */
        removeCost(_row, index) {
          this.form.costs.splice(index, 1);
        },
     
        /* 更新visible */
        updateVisible(value) {
          //更新父组件中的visible的值
          this.$emit('update:visible', value);
        },

        handleClose() {
          this.$emit('update:visible', false);
        },

        clickOrderNo(row){
          removePageTab({ key: '/businesshandling/purordermanager' });
          this.$nextTick(() => {
            this.$router.push({path: '/businesshandling/purordermanager', query: { "billNo": row.purOrderNo } });
          });
        },

        AddCost(isadd){
          this.showAddCost =true;
          this.current = this.form.costs?this.form.costs[0]:{} ;
          if(!this.current)this.current = {};
          this.current.isAdd = isadd;
          this.current.inOrderId = this.form.id;
        },

        // 打印
        print(){
          PrintInOrderById(this.form.id).then((data)=>{
            const pWindow = printHtml({
              html: data, // 要打印的内容
              // style: '<style>span { color: red; }</style>',  // 页面样式
              // title: '', // 页面标题，浏览器打印设置显示页眉会显示页面标题
              horizontal: true, // 是否横向打印
              blank: true, // 是否打开新页面打印
              close: true, // 如果是打开新页面，打印完是否关闭
              print: true, // 如果是打开新窗口是否自动打印
              iePreview: true, // 是否兼容 ie 打印预览
              loading: true, // 是否显示 loading
              before: () => { // 打印开始的回调
              },
              done: () => { // 打印完成的回调
              },
              margin: 0, // 页间距
              header: '', // 页眉 html
              footer: '' // 页脚 html
            });
          });
        },
    },
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
         
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.setData(this.data.id);
              this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={id:'',costs:[],clearAmount:0};
              this.isUpdate = false;
              let currentUser = getUser();
              this.$set(this.form,'inDate',this.defaultDate);
              this.$set(this.form,'operatorId',currentUser.accountId);
              this.$set(this.form,'operatorName',currentUser.accountName);
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form = {id:'',costs:[],clearAmount:0};
              let currentUser = getUser();
              this.form.operatorId = currentUser.accountId;
              this.form.inDate = this.defaultDate;
          }
        }
      }
    };
  </script>
  <style lang='scss' scoped>
   .hangs_two {
    width: 70%;
    color: chocolate;
    cursor: pointer;
    .text {
      text-decoration: underline;
      margin-right: 4px;
    }
    .iconfont {
      margin-right: 4px;
    }
  }
</style>